package com.leyou.user.web;

import com.leyou.auth.dto.UserDetail;
import com.leyou.auth.utils.UserContext;
import com.leyou.user.dto.UserDTO;
import com.leyou.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

/**
 * @author mySun
 * @create 2021-07-27 19:05
 */
@RestController
@RequestMapping("/info")
public class UserController {
    @Autowired
    private UserService userService;

    /**
     * 根据用户名和密码查询
     * @param username 用户名
     * @param password 密码
     * @return
     */
    @GetMapping
    public ResponseEntity<UserDTO> queryUserByUsernameAndPassword(
            @RequestParam("username") String username,
            @RequestParam("password") String password
    ){
        return ResponseEntity.ok(this.userService.queryUserByUsernameAndPassword(username,password));

    }

    /**
     * 注册
     * @param username 用户名
     * @param password 密码
     * @param phone 电话
     * @param code 验证码
     * @return
     */
    @PostMapping
    public ResponseEntity<Void> registry(
            @RequestParam("username")String username,
            @RequestParam("password")String password,
            @RequestParam("phone")String phone,
            @RequestParam("code")String code
    ){
        this.userService.registry(username,password,phone,code);
        return ResponseEntity.status(HttpStatus.CREATED).build();
    }

    /**
     * 发送短信验证码
     * @param phone 电话
     * @return
     */
    @PostMapping("/code")
    public ResponseEntity<Void> sendMessage(@RequestParam("phone")String phone){
        this.userService.sendMessage(phone);
        return ResponseEntity.ok().build();
    }

    /**
     * 判断信息是否存在
     * @param data 要检验的数据
     * @param type 数据的类型
     * @return 是否存在
     */
    @GetMapping("/exists/{data}/{type}")
    public ResponseEntity<Boolean> isExists(
            @PathVariable("data")String data,
            @PathVariable("type")Integer type
    ){
        return ResponseEntity.ok(this.userService.isExists(data,type));
    }

    /**
     * 用户登录成功后，从拦截器中获取用户数据并展示
     * @return
     */
    @GetMapping("/me")
    public ResponseEntity<UserDetail> showUser(){
        return ResponseEntity.ok(UserContext.getUser());
    }
}
